﻿'use strict';

zxcv.start = function (settings) {
    var doc = document,
        onReady;

    // 입력된 설정들을 검사하고 바로 잡습니다.
    settings = settings || {};
    settings.name   = settings.name   || '';
    settings.canvas = settings.canvas || '';
    settings.width  = settings.width  || 0;
    settings.height = settings.height || 0;
    settings.fps    = settings.fps    || 60;

    // 초기화는 문서가 준비된 이후로 미룹니다.
    if (doc.addEventListener) { // Firefox, Chrome, ...
        onReady = function () {
            doc.removeEventListener('DOMContentLoaded', onReady, false);
            zxcv.raw.startWeb(settings);
        };
        doc.addEventListener('DOMContentLoaded', onReady, false);
    }
    else if (doc.attachEvent) { // Internet Explorer
        onReady = function () {
            if (doc.readystate === 'complete') {
                doc.detachEvent('onreadystatechange', onReady);
                zxcv.raw.startWeb(settings);
            }
        };
        doc.attachEvent('onreadystatechange', onReady);
    }
    else { // Unknown
        zxcv.raw.startWeb(settings);
    }
};

zxcv.now = function () {
    return (new Date()).getTime();
};

zxcv.raw.startWeb = function (settings) {
    var raw = zxcv.raw,
        doc = document,
        canvas,
        assetBox, graphics, audio, input, renderer;

    // 설정에 입력된 ID를 가진 Canvas를 찾습니다. 만약 Canvas가 없다면 예외를 던집니다.
    canvas = doc.getElementById(settings.canvas);
    if (canvas === null)
        throw new Error('start failed, canvas not found. (' + settings.canvas + ')');

    // Canvas의 크기가 따로 입력되어 있다면 Canvas의 크기를 조정합니다.
    if (settings.width > 0 && settings.height > 0) {
        canvas.style.width  = settings.width  + 'px';
        canvas.style.height = settings.height + 'px';
    }
    
    assetBox = new raw.AssetBox();
    graphics = new raw.Graphics(canvas);
    audio    = new raw.Audio(canvas);
    input    = new raw.Input(canvas);
    renderer = new zxcv.Renderer();
    raw.start(settings, {assetBox:assetBox, graphics:graphics, audio:audio, input:input, renderer:renderer});
    raw.run();
};

zxcv.raw.run = (function () {
    var w = window,
        f = w.requestAnimationFrame || 
            w.webkitRequestAnimationFrame ||
            w.mozRequestAnimationFrame ||
            w.oRequestAnimationFrame ||
            w.msRequestAnimationFrame,
        frame = function () {
            var raw = zxcv.raw;
            raw.run();
            raw.tick();
        }

    if (f)
        return function () { f(frame); };
    else
        return function () { setTimeout(frame, 1000 / 60); };
})();